public class BM2V2 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || m == n) {
            return head;
        }

        // 使用 dummy 节点简化处理
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;

        // 找到 m 的前一个节点
        for (int i = 1; i < m; i++) {
            pre = pre.next;
        }

        // 使用三指针反转链表
        ListNode cur = pre.next;
        ListNode next;
        for (int i = m; i < n; i++) {
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }

        return dummy.next;
    }

    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // Create the linked list: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        // Define m and n for reversing the sublist from m to n
        int m = 2;
        int n = 4;

        // Reverse the sublist from m to n
        ListNode reversed = reverseBetween(head, m, n);

        // Print the reversed linked list
        printList(reversed);  // Output: 1 4 3 2 5
    }
}
